package org.ciallo.simplemusicplayer.fragment;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import org.ciallo.simplemusicplayer.R;
import org.ciallo.simplemusicplayer.adapter.SongAdapter;
import org.ciallo.simplemusicplayer.data.model.Song;
import org.ciallo.simplemusicplayer.dialog.SongOptionsDialogFragment;
import org.ciallo.simplemusicplayer.viewmodel.LocalMusicViewModel;
import org.ciallo.simplemusicplayer.viewmodel.SharedViewModel;
import timber.log.Timber;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Jukomu
 * @Description: 显示单曲列表的Fragment
 * 支持下拉刷新从媒体库加载歌曲
 * @Package: org.ciallo.simplemusicplayer.fragment
 * @Project: SimpleMusicPlayer
 * @name: SongListFragment
 * @Date: 2025/5/31-00:26
 * @Filename: SongListFragment
 */
public class SongListFragment extends Fragment {

    private RecyclerView recyclerViewSongs;
    private SongAdapter songAdapter;
    private LocalMusicViewModel localMusicViewModel;
    private SharedViewModel sharedViewModel; // 用于播放控制
    private TextView tvEmptyList;
    private SwipeRefreshLayout swipeRefreshLayout; // 下拉刷新控件

    // 权限请求启动器
    private ActivityResultLauncher<String> requestPermissionLauncher;


    public SongListFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 初始化权限请求回调
        requestPermissionLauncher = registerForActivityResult(new ActivityResultContracts.RequestPermission(), isGranted -> {
            if (isGranted) {
                Timber.i("Storage permission granted by user for SongListFragment.");
                triggerScanIfPermitted(); // 权限被授予后，尝试扫描
            } else {
                Timber.w("Storage permission denied by user for SongListFragment.");
                showPermissionDeniedUI();
                Toast.makeText(getContext(), "读取存储权限被拒绝，无法加载本地歌曲。", Toast.LENGTH_LONG).show();
            }
        });
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_generic_list, container, false);

        // ViewModel 初始化 (sharedViewModel 在这里初始化，或者从 requireActivity() 获取如果 MainActivity 已创建)
        sharedViewModel = new ViewModelProvider(requireActivity()).get(SharedViewModel.class);
        localMusicViewModel = new ViewModelProvider(this).get(LocalMusicViewModel.class); // 或者 requireActivity() 如果希望在 LocalMusicContainerFragment 的所有子 Tab 间共享同一个 LocalMusicViewModel 实例

        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        swipeRefreshLayout = view.findViewById(R.id.swipeRefreshLayout_generic_list);
        recyclerViewSongs = view.findViewById(R.id.recyclerView_generic);
        tvEmptyList = view.findViewById(R.id.textView_empty_list);
        tvEmptyList.setText(getString(R.string.empty_songs_message_swipe_refresh));

        setupRecyclerView();
        setupSwipeRefreshLayout();
        observeViewModel();

        triggerScanIfPermitted();
    }

    /**
     * 设置 RecyclerView 及其适配器。
     */
    private void setupRecyclerView() {
        songAdapter = new SongAdapter(
                (song, position) -> { // OnSongClickListener
                    // 点击歌曲项播放
                    List<Song> currentList = songAdapter.getCurrentList(); // 获取ListAdapter的当前列表
                    if (sharedViewModel != null && currentList != null && !currentList.isEmpty()) {
                        // 播放当前列表，并从点击的位置开始
                        Timber.d("SongListFragment: Attempting to play. Queue size to be sent: %d, Position: %d", currentList.size(), position);
                        sharedViewModel.playSongAtIndex(new ArrayList<>(currentList), position);

                        // 可选：点击后跳转到播放界面
                        // if (getActivity() != null) {
                        //     startActivity(new Intent(getActivity(), PlayerActivity.class));
                        // }
                    } else {
                        Timber.w("Cannot play song: SharedViewModel or song list is null/empty.");
                    }
                },
                (song, anchorView) -> { // OnSongOptionsClickListener
                    if (getChildFragmentManager() != null && song != null) {
                        // 使用新的 SongOptionsDialogFragment，并传递 songId
                        // 如果是从歌单列表触发，第二个参数是 playlistIdContext，这里是单曲列表，所以传 INVALID_INDEX
                        SongOptionsDialogFragment.newInstance(song.getId())
                                .show(getChildFragmentManager(), SongOptionsDialogFragment.TAG);
                    }
                }
        );
        recyclerViewSongs.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerViewSongs.setAdapter(songAdapter);
    }

    /**
     * 设置 SwipeRefreshLayout 的下拉刷新监听。
     */
    private void setupSwipeRefreshLayout() {
        swipeRefreshLayout.setOnRefreshListener(() -> {
            Timber.d("Swipe to refresh triggered.");
            triggerScanIfPermitted(); // 用户下拉时，检查权限并触发扫描
        });

        // (可选) 设置刷新指示器的颜色
        if (getContext() != null) {
            swipeRefreshLayout.setColorSchemeColors(
                    ContextCompat.getColor(getContext(), R.color.md_theme_light_primary), // 与你的主题颜色匹配
                    ContextCompat.getColor(getContext(), R.color.md_theme_light_secondary)
            );
        }
    }

    /**
     * 观察 ViewModel 中的 LiveData。
     */
    private void observeViewModel() {
        // 1. 观察 SharedViewModel 中的搜索查询词变化
        sharedViewModel.currentSearchQuery.observe(getViewLifecycleOwner(), query -> {
            Timber.d("SongListFragment: Observed search query change from SharedViewModel: '%s'", query);
            // 当 SharedViewModel 中的搜索词变化时，通知 LocalMusicViewModel 更新其内部查询
            localMusicViewModel.updateSearchQuery(query);
        });

        // 2. 观察 LocalMusicViewModel 中的扫描状态
        localMusicViewModel.getScanningStatus().observe(getViewLifecycleOwner(), isScanning -> {
            if (isScanning != null) {
                swipeRefreshLayout.setRefreshing(isScanning);
                if (isScanning) {
                    tvEmptyList.setVisibility(View.GONE);
                }
            }
        });

        // 3. 观察 LocalMusicViewModel 中最终要显示的歌曲列表
        localMusicViewModel.songsToDisplay.observe(getViewLifecycleOwner(), songs -> {
            Timber.d("SongListFragment: songsToDisplay updated. Count: %d", songs != null ? songs.size() : 0);
            Boolean isLoading = localMusicViewModel.getScanningStatus().getValue(); // 也考虑扫描状态
            Boolean searchActive = sharedViewModel.currentSearchQuery.getValue() != null && !sharedViewModel.currentSearchQuery.getValue().isEmpty();

            if (songs != null && !songs.isEmpty()) {
                songAdapter.submitList(new ArrayList<>(songs));
                tvEmptyList.setVisibility(View.GONE);
                recyclerViewSongs.setVisibility(View.VISIBLE);
            } else {
                songAdapter.submitList(new ArrayList<>());
                recyclerViewSongs.setVisibility(View.GONE);
                // 只有在非加载/扫描状态时，才根据是否有搜索词来决定空状态文本
                if (isLoading == null || !isLoading) {
                    if (searchActive) {
                        tvEmptyList.setText("没有找到与“" + sharedViewModel.currentSearchQuery.getValue() + "”相关的歌曲");
                    } else {
                        tvEmptyList.setText(getString(R.string.empty_songs_message_swipe_refresh));
                    }
                    tvEmptyList.setVisibility(View.VISIBLE);
                } else {
                    tvEmptyList.setVisibility(View.GONE); // 正在加载/扫描时，不显示空列表文字
                }
            }
        });
    }

    /**
     * 检查读取存储权限，如果已授予则触发媒体库扫描，否则请求权限。
     */
    private void triggerScanIfPermitted() {
        if (getContext() == null) return;

        String permissionToRequest;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            permissionToRequest = Manifest.permission.READ_MEDIA_AUDIO;
        } else {
            permissionToRequest = Manifest.permission.READ_EXTERNAL_STORAGE;
        }

        if (ContextCompat.checkSelfPermission(requireContext(), permissionToRequest) == PackageManager.PERMISSION_GRANTED) {
            Timber.d("Permission granted. Starting media scan.");
            localMusicViewModel.startMediaStoreScan(); // 已有权限，开始扫描
        } else {
            Timber.d("Permission not granted. Requesting permission: %s", permissionToRequest);
            // 权限未授予，请求权限
            // 可以先显示一个理由对话框 (shouldShowRequestPermissionRationale)
            if (ActivityCompat.shouldShowRequestPermissionRationale(requireActivity(), permissionToRequest)) {
                new AlertDialog.Builder(requireContext())
                        .setTitle("权限请求")
                        .setMessage("播放器需要读取您的音频文件才能显示本地音乐。")
                        .setPositiveButton("授予权限", (dialog, which) -> requestPermissionLauncher.launch(permissionToRequest))
                        .setNegativeButton("取消", (dialog, which) -> {
                            swipeRefreshLayout.setRefreshing(false); // 如果用户取消，停止刷新动画
                            showPermissionDeniedUI();
                        })
                        .show();
            } else {
                requestPermissionLauncher.launch(permissionToRequest); // 直接请求
            }
        }
    }

    /**
     * 当权限被拒绝时，更新UI以提示用户。
     */
    private void showPermissionDeniedUI() {
        if (tvEmptyList != null && recyclerViewSongs != null) {
            tvEmptyList.setText("未授予读取权限，无法加载歌曲。\n请在应用设置中开启权限后下拉刷新。");
            tvEmptyList.setVisibility(View.VISIBLE);
            recyclerViewSongs.setVisibility(View.GONE);
            if (swipeRefreshLayout != null) {
                swipeRefreshLayout.setRefreshing(false);
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        // 当Fragment返回前台时，可以考虑是否需要自动刷新或检查权限
        // 例如，如果用户从设置页面返回，权限可能已更改
        // 但频繁自动扫描可能不是好的体验，交给用户下拉刷新更佳
    }
}
